package io.github.controller.admin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import io.github.annotation.Log;
import io.github.entity.*;
import io.github.service.*;
import io.github.util.ExcelUtil;
import io.github.util.PageUtils;
import io.github.util.R;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author: weil
 * @date: 2019/9/18 20:27
 * @version: 1.0
 * @description:
 */
@RestController
@RequestMapping("/admin/sys/control")
public class SysCallConController extends AbstractController {

    @Resource
    private SysAreaServive sysAreaServive;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysCallControlService sysCallControlService;
    @Resource
    private SysEquipmentService sysEquipmentService;

    @Resource
    private SysGatewayService sysGatewayService;

    /**
     * 所有呼叫控制列表
     */
    @RequestMapping("/list")
    @Log(value="呼叫控制查询",action = 0)
    public R list(@RequestBody JSONObject jsonObject) {
        logger.info("呼叫控制数据接口");
        //获取前端传的值
        Integer offset = jsonObject.getInteger("offset");

        Integer limit = jsonObject.getInteger("limit");

        String gatewayFrom = jsonObject.getString("gatewayFrom");

        String gateway = jsonObject.getString("gateway");

        Page<SysCallControlEntity> adminList = sysCallControlService.queryListByPage(offset, limit,gatewayFrom,gateway);
        List<SysCallControlEntity> records = adminList.getRecords();


        //通过登录用户id-->>获取地区id数据
        SysUserEntity userEntity = sysUserService.selectById(getAdminId());
        //分隔地区id
        String[] areaid = userEntity.getAreaid().split(",");
        List<String> list = new ArrayList<String>();
        //获取所有地区id对应的设备编号
        for (String area : areaid) {
            List<SysEquipmentEntity> equipmentList = sysEquipmentService.selectByAreaid(area);

            for (SysEquipmentEntity entity : equipmentList) {
                //获取地区id
                String areaid1 = entity.getAreaid();
                list = sysEquipmentService.queryEquipnumList(areaid1);

            }
        }

        PageUtils pageUtil = new PageUtils(records, adminList.getTotal(), adminList.getSize(),
                adminList.getCurrent());

        return R.ok().put("page", pageUtil);
    }

    /**
     * 呼叫控制增加
     */
    @Log(value="呼叫控制添加",action = 1)
    @RequestMapping("/add")
    public R save(@RequestBody SysCallControlEntity entity) {

        String gatewayFromId = entity.getGatewayFromId();
        //通过gatewayFromId 获取 gateway
        SysGatewayEntity gw = sysGatewayService.getById(Integer.parseInt(gatewayFromId));

        entity.setIp(gw.getIp());

        sysCallControlService.save(entity);

        return R.ok();
    }

    /**
     * 2019年11月11日 弄个接口给别人调用 对router 进行操作
     */
    @RequestMapping("/router")
    public R router(@RequestBody JSONObject json){
        String action = json.getString("action");
        String reqid = json.getString("reqid");

        if(action.equals("add")){
            String telFrom = json.getString("tel_from");//主叫号码匹配
            String transferFrom = json.getString("transfer_from"); //变换主叫号码匹配
            String telTo = json.getString("tel_to"); //被叫号码匹配
            String transferTo = json.getString("transfer_to");
            String ipFrom = json.getString("ip_from");
            String remark = json.getString("company");
            String gatewayId = null;
            String gateway = json.getString("gateway");
            if(StringUtils.isBlank(gateway)){
                //如果gateway 为空 意思就是传的是remark
                String result = sysGatewayService.getByRemark(remark);
                gatewayId = result.split(",")[0];
                gateway = result.split(",")[1];
            }else{
                //如果 传的是  name
                String result = sysGatewayService.getByName(gateway);
                gatewayId = result.split(",")[0];
                remark = result.split(",")[1];
            }
            SysCallControlEntity entity = new SysCallControlEntity();
            entity.setTelFrom(telFrom);
            entity.setTransferFrom(transferFrom);
            entity.setTelTo(telTo);
            entity.setTransferTo(transferTo);
            entity.setIp(ipFrom);
            entity.setGateway(gateway);
            entity.setGatewayId(gatewayId);
            entity.setToName(remark);
            sysCallControlService.save(entity);
            return R.ok().put("reason","success").put("reqid",reqid).put("result","0");

        } else if(action.equals("delete")){
            String telTo = json.getString("tel_to");
            String uuid = json.getString("id");
            if(StringUtils.isNotBlank(uuid)){
                sysCallControlService.deleteByReqid(uuid);
            }else {
                sysCallControlService.deleteByTel(telTo);
            }
            return R.ok().put("reason","success").put("reqid",reqid).put("result","0");
        } else {
            return R.error();
        }
    }

    /**
     * 呼叫控制删除
     */
    @Log(value="呼叫控制删除",action = 3)
    @RequestMapping("/delete")
    public R delete(@RequestBody JSONObject jsonObject) {
        logger.info("呼叫控制删除接口");
        String idStr = jsonObject.getString("ids");
        System.out.println(">>>>>idStr:" + idStr);
        String ids = "[" + idStr + "]";
        System.out.println(">>>>>ids:" + ids);
        JSONArray jsonArray = JSONArray.parseArray(ids);
        Long[] conIds = toArrays(jsonArray);
        if (conIds.length < 1) {
            return R.error(500, "请选择要删除的数据");
        }
        sysCallControlService.deleteBatch(conIds);
        return R.ok();
    }

    /**
     * 呼叫控制修改
     */
    @Log(value="呼叫控制修改",action = 2)
    @RequestMapping("/update")
    public R update(@RequestBody SysCallControlEntity entity) {
        logger.info("呼叫控制修改接口");
        Long conId = entity.getId();
        SysCallControlEntity controlEntity = new SysCallControlEntity();
        //主叫号码匹配
        controlEntity.setTelFrom(entity.getTelFrom());
        //被叫号码匹配
        controlEntity.setTransferFrom(entity.getTransferFrom());
        //备注
        controlEntity.setRemark(entity.getRemark());

        sysCallControlService.updateRouter(entity, conId);
        return R.ok().put("con", entity);

    }

    /**
     * 呼叫控制导出
     */
    @Log(value = "呼叫控制导出",action = 7)
    @RequestMapping("/export")
    public R export(HttpServletResponse response) throws IOException {
        logger.info("呼叫控制导出接口");
        List<List<String>> excelData = new ArrayList<>();

        List<String> head = new ArrayList<>();

        List<SysCallControlEntity> list = sysCallControlService.queryAllRouter();

        for (int i = 0; i < list.size(); i++) {
            List<String> data = new ArrayList<>();
            data.add(list.get(i).getIp());
            data.add(list.get(i).getTelFrom());
            data.add(list.get(i).getTransferTo());
            data.add(list.get(i).getRemark());

            excelData.add(data);
        }
        excelData.add(head);

        String sheetName = "data";
        String fileName = "data.xls";

        ExcelUtil.exportExcel(response, excelData, sheetName, fileName, 15);
        return R.ok();
    }
}
